<?php 
namespace app\dboard\logic;
use think\Db;

class Index extends Base{

	public $freight_order_status = ['1'=>'待处理','2'=>'已处理','3'=>'撤销'];
	public function __construct()
	{
		parent::__construct();
	}

	// 装车任务管理
	public function crewmanTask($input)
	{
		$map = 'ct.status in (0,1) and pb.status=4 and p.port_id='.$this->AccountInfo['AccountPortId'];
        $total = Db::name('crewman_task')->alias('ct')
        		->leftJoin('position_box pb','ct.position_box_id=pb.id')
        		->leftJoin('position p','pb.position_id=p.id')
        		->where($map)->count();
        $limit = isset($input['length'])?$input['length']:10;
        $filter_count = ceil($total/$limit)*$limit;
        $start = isset($input['start'])?($input['start']/10)*$limit:0;
        $order = 'ct.id DESC';
        $field = 'ct.id,pb.task_time,p.transverse_letter,p.portrait_letter,pb.box_no,ct.transport_ship_no,ct.box_number,ct.position_box';
        $data_list = Db::name('crewman_task')->alias('ct')->field($field)
        		->leftJoin('position_box pb','ct.position_box_id=pb.id')
        		->leftJoin('position p','pb.position_id=p.id')
        		->where($map)->order($order)->select();
        foreach($data_list as &$val){
            $val['task_time'] = date('Y-m-d H:i:s',$val['task_time']);
        }
        return [$total,$filter_count,$data_list];
	}

	/**
	  * 空箱提出后堆放位状态变成空位
	  * 此时堆放位整体需要转换状态，具体就是最底下的箱子提出后上面的箱子会往下移，堆放位的box_no和状态跟着变
	  * 这里箱子的操作分为几个阶段：
	  * 1.空箱吊出任务，操作的是待提
	  * 2.从驳船上卸下来进场任务，操作的是空位
	  * 3.待提箱装车任务，操作的是待提
	  * 4.装完车后还箱任务，操作的是空位
	**/
	public function empty_position($position_box_id)
	{
		$position_box = Db::name('position_box')->field('id,box_no,position_id')->where('id',$position_box_id)->find();
		$need_change_box = Db::name('position_box')->field('id,position_id,box_no,status')->where('box_no >= '.$position_box['box_no'].' and position_id='.$position_box['position_id'])->order('box_no ASC')->select();
		if (count($need_change_box)) {
			foreach ($need_change_box as $key => $value) {
				// 最上面的堆放位状态变成空位
				if ($key==0) {
					// 更新箱子状态
					$pb_update = Db::name('position_box')->where('id='.$value['id'])->update(['box_no'=>$need_change_box[count($need_change_box)-1]['box_no'],'update_time'=>now_time()]);
					if (!$pb_update) {
						return false;
					}
				}
				// 下面的箱子改变状态，并改变吊机员和堆放位任务的箱号
				if ($key>0) {
					// 更新箱子状态
					$pb_update = Db::name('position_box')->where('id='.$value['id'])->update(['box_no'=>$need_change_box[$key-1]['box_no'],'update_time'=>now_time()]);
					if (!$pb_update) {
						return false;
					}
					// 空箱的时候，无其他表要改变
					if ($value['status']==1) {
					}
					// 重箱的时候，进场的堆放位需要改变，吊机员空箱吊出任务操作堆放位需要改变
					if ($value['status']==2) {
						$invoice_info = Db::name('invoice_info')->field('id')->where(['position_box_id'=>$value['id'],'status'=>0])->find();
						if ($invoice_info) {
							$position = Db::name('position')->field('transverse_letter,portrait_letter')->where('id',$value['position_id'])->find();
							$ii_update = Db::name('invoice_info')->where('id',$invoice_info['id'])->update(['position_box'=>$position['transverse_letter'].'-'.$position['portrait_letter'].'-'.$need_change_box[$key-1]['box_no'],'update_time'=>now_time()]);
							if (!$ii_update) {
								return false;
							}
						}
						$crewman_task_new = Db::name('crewman_task')->field('id')->where(['position_box_id'=>$value['id'],'status'=>1])->find();
						if ($crewman_task_new) {
							$position = Db::name('position')->field('transverse_letter,portrait_letter')->where('id',$value['position_id'])->find();
							$ct_update = Db::name('crewman_task')->where('id',$crewman_task_new['id'])->update(['position_box'=>$position['transverse_letter'].'-'.$position['portrait_letter'].'-'.$need_change_box[$key-1]['box_no'],'update_time'=>now_time()]);
							if (!$ct_update) {
								return false;
							}
						}
					}
					// 空位的时候，无其他表要改变
					if ($value['status']==3) {
					}
					// 待提的时候，空箱吊出时吊机员装车任务的操作箱子需要改变，进场时吊机员任务和进场的堆放位需要改变
					if ($value['status']==4) {
						// 进场任务
						$crewman_task_new = Db::name('crewman_task')->field('id,type')->where(['position_box_id'=>$value['id'],'status'=>1,'type'=>1])->find();
						if ($crewman_task_new) {
							$position = Db::name('position')->field('transverse_letter,portrait_letter')->where('id',$value['position_id'])->find();
							$ct_where = ['position_box'=>$position['transverse_letter'].'-'.$position['portrait_letter'].'-'.$need_change_box[$key-1]['box_no'],'update_time'=>now_time()];
							$ct_update = Db::name('crewman_task')->where('id',$crewman_task_new['id'])->update($ct_where);
							if (!$ct_update) {
								return false;
							}
							$invoice_info = Db::name('invoice_info')->field('id')->where(['position_box_id'=>$value['id'],'status'=>0])->find();
							if ($invoice_info) {
								$position = Db::name('position')->field('transverse_letter,portrait_letter')->where('id',$value['position_id'])->find();
								$ii_update = Db::name('invoice_info')->where('id',$invoice_info['id'])->update(['position_box'=>$position['transverse_letter'].'-'.$position['portrait_letter'].'-'.$need_change_box[$key-1]['box_no'],'update_time'=>now_time()]);
								if (!$ii_update) {
									return false;
								}
							}
						}
						// 空箱提箱任务
						$crewman_task_new = Db::name('crewman_task')->field('id,type')->where(['position_box_id'=>$value['id'],'status'=>0,'type'=>2])->find();
						if ($crewman_task_new) {
							$position = Db::name('position')->field('transverse_letter,portrait_letter')->where('id',$value['position_id'])->find();
							$ct_where = ['position_box'=>$position['transverse_letter'].'-'.$position['portrait_letter'].'-'.$need_change_box[$key-1]['box_no'],'update_time'=>now_time()];
							$ct_update = Db::name('crewman_task')->where('id',$crewman_task_new['id'])->update($ct_where);
							if (!$ct_update) {
								return false;
							}
						}
					}
				}
			}
		}
		return true;
	}

	// 装车
	public function loadCar($param)
	{
		$crewman_task = Db::name('crewman_task')->field('*')->where('id',$param['id'])->find();
		if (!$crewman_task) {
            $this->error_data['ErrorMsg'] = '不存在该任务';
            return $this->printResult($this->error_data);
		}
		if (!in_array($crewman_task['status'],[0,1])) {
            $this->error_data['ErrorMsg'] = '当前箱状态有误';
            return $this->printResult($this->error_data);
		}
		try {
			Db::startTrans();
			// 空箱任务
			if ($crewman_task['type']==2) {
				$data['status'] = 4; // 已装车
				$data['update_time'] = now_time();
				$update = Db::name('crewman_task')->where('id',$param['id'])->update($data);
				if (!$update) {
					Db::rollback();
		            $this->error_data['ErrorMsg'] = '发送失败';
		            return $this->printResult($this->error_data);
				}
				$pb_data['status'] = 3;
				$pb_data['box_number'] = '';
				$pb_data['entrance_time'] = 0;
				$pb_data['task_time'] = 0;
				$pb_data['update_time'] = now_time();
				$pb_update = Db::name('position_box')->where('id',$crewman_task['position_box_id'])->update($pb_data);
				if (!$pb_update) {
					Db::rollback();
		            $this->error_data['ErrorMsg'] = '发送失败';
		            return $this->printResult($this->error_data);
				}




				$res = $this->empty_position($crewman_task['position_box_id']);
				if (!$res) {
					Db::rollback();
		            $this->error_data['ErrorMsg'] = '发送失败';
		            return $this->printResult($this->error_data);
				}
				Db::commit();
		        $this->error_data['ErrorCode'] = 1;
		        $this->error_data['ErrorMsg'] = '发送成功';
		        return $this->printResult($this->error_data);
			}
			// 重箱任务
			$data['status'] = 2; // 已装车
			$data['load_car_time'] = $data['update_time'] = now_time();
			$update = Db::name('crewman_task')->where('id',$param['id'])->update($data);
			if (!$update) {
				Db::rollback();
	            $this->error_data['ErrorMsg'] = '发送失败';
	            return $this->printResult($this->error_data);
			}
			$update_id = Db::name('invoice')->where('id',$crewman_task['invoice_id'])->update(['status'=>1,'update_time'=>now_time()]);
			if (!$update_id) {
				Db::rollback();
	            $this->error_data['ErrorMsg'] = '发送失败';
	            return $this->printResult($this->error_data);
			}
			$i_update_id = Db::name('invoice_info')->where('invoice_id',$crewman_task['invoice_id'])->update(['status'=>2,'update_time'=>now_time()]);
			if (!$i_update_id) {
				Db::rollback();
	            $this->error_data['ErrorMsg'] = '发送失败';
	            return $this->printResult($this->error_data);
			}
			$pb_data['status'] = 3;
			$pb_data['box_number'] = '';
			$pb_data['entrance_time'] = 0;
			$pb_data['task_time'] = 0;
			$pb_data['update_time'] = now_time();
			$pb_update = Db::name('position_box')->where('id',$crewman_task['position_box_id'])->update($pb_data);
			if (!$pb_update) {
				Db::rollback();
	            $this->error_data['ErrorMsg'] = '发送失败';
	            return $this->printResult($this->error_data);
			}
			$res = $this->empty_position($crewman_task['position_box_id']);
			Db::commit();
	        $this->error_data['ErrorCode'] = 1;
	        $this->error_data['ErrorMsg'] = '发送成功';
	        return $this->printResult($this->error_data);
		} catch (\Exception $e) {
			Db::rollback();
            $this->error_data['ErrorMsg'] = '服务器繁忙';
            return $this->printResult($this->error_data);
		}
	}

	// 用户列表
	public function userList($input)
	{
		$map = '1=1 ';
        if (isset($input['filter_param']['start_time']) && !empty($input['filter_param']['start_time'])) {
        	$map .= ' and create_time>'.$input['filter_param']['start_time'];
        }
        if (isset($input['filter_param']['end_time']) && !empty($input['filter_param']['end_time'])) {
        	$map .= ' and create_time<'.$input['filter_param']['end_time'];
        }
        if (isset($input['filter_param']['nickname']) && !empty($input['filter_param']['nickname'])) {
        	$map .= ' and nickname like "%'.$input['filter_param']['nickname'].'%"';
        }
        $total = Db::name('user')->where($map)->count();
        $limit = isset($input['length'])?$input['length']:10;
        $filter_count = ceil($total/$limit)*$limit;
        $start = isset($input['start'])?($input['start']/10)*$limit:0;
        $order = 'id DESC';
        $field = '*';
        $data_list = Db::name('user')->field($field)->where($map)->order($order)->select();
        foreach($data_list as &$val){
            $val['create_time'] = date('Y-m-d H:i:s',$val['create_time']);
        }
        return [$total,$filter_count,$data_list];
	}

	// 改变用户状态
	public function changeUserStatus($param)
	{
		$user = Db::name('user')->where('id',$param['id'])->find();
		if (!$user) {
            $this->error_data['ErrorMsg'] = '不存在该用户';
            return $this->printResult($this->error_data);
		}
		if ($user['status']==$param['status']) {
            $this->error_data['ErrorMsg'] = '提交状态有误';
            return $this->printResult($this->error_data);
		}
		$update = Db::name('user')->where('id',$param['id'])->update(['status'=>$param['status'],'update_time'=>now_time()]);
		if (!$update) {
            $this->error_data['ErrorMsg'] = '更改状态失败';
            return $this->printResult($this->error_data);
		}
        $this->error_data['ErrorCode'] = 1;
        $this->error_data['ErrorMsg'] = '操作成功';
        return $this->printResult($this->error_data);
	}

	// 货运需求列表,$type=0：未处理,$type=1：已处理
	public function freightOrderTask($input,$type = 0)
	{
		if ($type) {
        	$map = 'fo.status !=1';
		} else {
        	$map = 'fo.status =1';
		}
        if (isset($input['filter_param']['start_time']) && !empty($input['filter_param']['start_time'])) {
        	$map .= ' and fo.create_time>'.$input['filter_param']['start_time'];
        }
        if (isset($input['filter_param']['end_time']) && !empty($input['filter_param']['end_time'])) {
        	$map .= ' and fo.create_time<'.$input['filter_param']['end_time'];
        }
        if (isset($input['filter_param']['phone']) && !empty($input['filter_param']['phone'])) {
        	$map .= ' and u.phone like "%'.$input['filter_param']['phone'].'%"';
        }
        $total = Db::name('freight_order')->alias('fo')
        		->leftJoin('user u','u.id=fo.uid')
        		->where($map)->count();
        $limit = isset($input['length'])?$input['length']:10;
        $filter_count = ceil($total/$limit)*$limit;
        $start = isset($input['start'])?($input['start']/10)*$limit:0;
        $order = 'fo.id DESC';
        $field = 'fo.*,u.nickname,u.phone';
        $data_list = Db::name('freight_order')->alias('fo')
        		->field($field)
        		->leftJoin('user u','u.id=fo.uid')
        		->where($map)->order($order)->select();
        foreach($data_list as &$val){
            $val['use_time'] = date('Y-m-d H:i:s',$val['use_time']);
            $val['create_time'] = date('Y-m-d H:i:s',$val['create_time']);
            $val['status_name'] = $this->freight_order_status[$val['status']];
        }
        return [$total,$filter_count,$data_list];
	}

	// 改变货运需求状态
	public function changeStatus($param)
	{
		$freight_order = Db::name('freight_order')->where('id',$param['id'])->find();
		if (!$freight_order) {
            $this->error_data['ErrorMsg'] = '不存在该需求单';
            return $this->printResult($this->error_data);
		}
		if ($freight_order['status']!=1) {
            $this->error_data['ErrorMsg'] = '需求单状态有误';
            return $this->printResult($this->error_data);
		}
		$update = Db::name('freight_order')->where('id',$param['id'])->update(['status'=>$param['status'],'update_time'=>now_time()]);
		if (!$update) {
            $this->error_data['ErrorMsg'] = '更改状态失败';
            return $this->printResult($this->error_data);
		}
        $this->error_data['ErrorCode'] = 1;
        $this->error_data['ErrorMsg'] = '操作成功';
        return $this->printResult($this->error_data);
	}

	// 物品类型
	public function itemTypeList($input)
	{
		$map = 'status=1';
        $total = Db::name('item_type')->where($map)->count();
        $limit = isset($input['length'])?$input['length']:10;
        $filter_count = ceil($total/$limit)*$limit;
        $start = isset($input['start'])?($input['start']/10)*$limit:0;
        $order = 'id DESC';
        $field = '*';
        $data_list = Db::name('item_type')->field($field)->where($map)->order($order)->select();
        foreach($data_list as &$val){
        }
        return [$total,$filter_count,$data_list];
	}

	// 添加编辑物品类型
	public function addEditItemType($param)
	{
		if (isset($param['id']) && $param['id']>0) {
			$update = Db::name('item_type')->where('id',$param['id'])->update(['name'=>$param['name'],'update_time'=>now_time()]);
			if (!$update) {
		        $this->error_data['ErrorMsg'] = '操作失败';
		        return $this->printResult($this->error_data);
			}
	        $this->error_data['ErrorCode'] = 1;
	        $this->error_data['ErrorMsg'] = '操作成功';
	        return $this->printResult($this->error_data);
		}
		$data['name'] = $param['name'];
		$data['status'] = 1;
		$data['create_time'] = now_time();
		$insert = Db::name('item_type')->insertGetId($data);
		if (!$insert) {
	        $this->error_data['ErrorMsg'] = '操作失败';
	        return $this->printResult($this->error_data);
		}
        $this->error_data['ErrorCode'] = 1;
        $this->error_data['ErrorMsg'] = '操作成功';
        return $this->printResult($this->error_data);
	}

	// 箱柜尺寸列表
	public function sizeList($input)
	{
		$map = 'status=1';
        $total = Db::name('size')->where($map)->count();
        $limit = isset($input['length'])?$input['length']:10;
        $filter_count = ceil($total/$limit)*$limit;
        $start = isset($input['start'])?($input['start']/10)*$limit:0;
        $order = 'id DESC';
        $field = '*';
        $data_list = Db::name('size')->field($field)->where($map)->order($order)->select();
        foreach($data_list as &$val){
        }
        return [$total,$filter_count,$data_list];
	}

	// 添加编辑箱柜尺寸
	public function addEditSize($param)
	{
		if (isset($param['id']) && $param['id']>0) {
			$update = Db::name('size')->where('id',$param['id'])->update(['size'=>$param['size'],'update_time'=>now_time()]);
			if (!$update) {
		        $this->error_data['ErrorMsg'] = '操作失败';
		        return $this->printResult($this->error_data);
			}
	        $this->error_data['ErrorCode'] = 1;
	        $this->error_data['ErrorMsg'] = '操作成功';
	        return $this->printResult($this->error_data);
		}
		$data['size'] = $param['size'];
		$data['status'] = 1;
		$data['create_time'] = now_time();
		$insert = Db::name('size')->insertGetId($data);
		if (!$insert) {
	        $this->error_data['ErrorMsg'] = '操作失败';
	        return $this->printResult($this->error_data);
		}
        $this->error_data['ErrorCode'] = 1;
        $this->error_data['ErrorMsg'] = '操作成功';
        return $this->printResult($this->error_data);
	}

	// banner列表
	public function bannerList($input)
	{
		$map = 'status=1';
        $total = Db::name('banner')->where($map)->count();
        $limit = isset($input['length'])?$input['length']:10;
        $filter_count = ceil($total/$limit)*$limit;
        $start = isset($input['start'])?($input['start']/10)*$limit:0;
        $order = 'id DESC';
        $field = '*';
        $data_list = Db::name('banner')->field($field)->where($map)->order($order)->select();
        foreach($data_list as &$val){
        	$val['photo'] = get_newpic_url($val['photo']);
        	$val['create_time'] = date('Y-m-d H:i:s',$val['create_time']);
        }
        return [$total,$filter_count,$data_list];
	}

	// 添加编辑banner
	public function addEditBanner($param)
	{
		if (isset($param['id']) && $param['id']>0) {
			$update = Db::name('banner')->where('id',$param['id'])->update(['title'=>$param['title'],'link'=>$param['link'],'photo'=>$param['photo'],'update_time'=>now_time()]);
			if (!$update) {
		        $this->error_data['ErrorMsg'] = '操作失败';
		        return $this->printResult($this->error_data);
			}
	        $this->error_data['ErrorCode'] = 1;
	        $this->error_data['ErrorMsg'] = '操作成功';
	        return $this->printResult($this->error_data);
		}
		if (isset($param['title'])) {
			$data['title'] = $param['title'];
		}
		if (isset($param['title'])) {
			$data['link'] = $param['link'];
		}
		$data['photo'] = $param['photo'];
		$data['status'] = 1;
		$data['create_time'] = now_time();
		$insert = Db::name('banner')->insertGetId($data);
		if (!$insert) {
	        $this->error_data['ErrorMsg'] = '操作失败';
	        return $this->printResult($this->error_data);
		}
        $this->error_data['ErrorCode'] = 1;
        $this->error_data['ErrorMsg'] = '操作成功';
        return $this->printResult($this->error_data);
	}
}

 ?>
